from robot.api import logger

from .antd_page_element import AntdPageElement
from ...common.element_function import ElementFunction
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Switch(AntdPageElement):

    def setValue(self, value=None):
        current_value = self.getValue()
        if value is None:
            set_value = not current_value
        else:
            if value.upper() == 'ON' or value == '开' or value == '启用':
                set_value = True
            elif value.upper() == 'OFF' or value == '关' or value == '禁用':
                set_value = False
            else:
                raise TestException.by_error_code(ErrorCode.SWITCH_BUTTON_NOT_SUPPORT_VALUE, value=value)
        if current_value != set_value:
            ElementFunction(self._driver).click(self._get_web_element())
            if self.getValue() != set_value:
                raise TestException.by_error_code(ErrorCode.ELEMENT_OPERATE_FAILED,
                                                  message='switch button set {0} failed'.format(value))
        else:
            logger.debug('The switch button is {}, not need changed.'.format(current_value))

    def getValue(self):
        # 根据span找，更加准确点
        if 'ant-switch-checked' in self._get_web_element().get_attribute('class'):
            return True
        else:
            return False

    def get_identification(self):
        identification = {'class': ['ant-switch'],
                          'tag': ['button']}
        return identification
